<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称" prop="Role_Name">
      <el-input v-model="ruleForm.Role_Name" />
    </el-form-item>
    <el-form-item label="状态" prop="Role_State">
      <el-radio-group v-model="ruleForm.Role_State">
        <el-radio :value="true">启用</el-radio>
        <el-radio :value="false">禁用</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="权限">
       <el-tree
            style="max-width: 600px"
            :data="data"
            show-checkbox
            node-key="id"
            ref="treeRef"
            :props="defaultProps"
            v-model="ruleForm.Permission_Id"
        />
    </el-form-item>
  
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { ElTree, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'

//声明Tree组件的实例，通过ref属性   InstanceType:获取组件的实例类型
const treeRef=ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  children: 'children',
  label: 'label',
}
const data = ref([]);

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  Role_Name: '',
  Role_State: true,
  Permission_Id: ''
})

//表单验证
const rules = reactive<FormRules>({
  Role_Name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' }
  ]
})

//表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      
      //获取表单元素数据
      console.log(ruleForm.Role_Name);
      console.log(ruleForm.Role_State);

      //获取树形组件选中的数据
      console.log(treeRef.value?.getCheckedKeys());

      axios.post('/api/Members/AddRolePermission?perLists='+treeRef.value?.getCheckedKeys(), 
        {
          Role_Name:ruleForm.Role_Name,
          Role_State:ruleForm.Role_State
        }
      )
      .then(res=>{
        console.log(res.data.data);
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(()=>{
    LoadData();
})

const LoadData=()=>{
    axios.get('/api/Members/ShowPermission?parentId=0')
    .then(res=>{
        data.value=res.data.data;
    })
}

</script>
